package cn.uyunsky.platform.util;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Map;
import java.util.UUID;

import cn.uyunsky.platform.data.JsonTool;
import cn.uyunsky.platform.jdbc.page.PageRequestFactory;
import cn.uyunsky.platform.util.pl.HibernateTemplateHelper;
import cn.uyunsky.platform.util.pl.PropertiesHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.ObjectUtils;

import cn.uyunsky.platform.util.other.MD5Tool;
import cn.uyunsky.platform.util.pl.DateHelper;

/**
 * 
 * <p>Description: 平台工具类,将other中的工具类常用方法放到这里同步调用
 * 一些方法都是引用其他开源包中方法,这里封装一边用于提醒</p>
 * @version 1.0
 * @date 2012-1-6
 */
public class PL {

	//全局日期格式化方式;其他地方不再重复定义
	public static final String DATE_FORMAT = "yyyy-MM-dd";
	public static final String TIME_FORMAT = "HH:mm:ss";
	public static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss";

	public static JsonTool JSON = new JsonTool();
	public static DateHelper DATE = new DateHelper();
    public static HibernateTemplateHelper hibernateTemplateHelper = new HibernateTemplateHelper();
    public static PageRequestFactory pageRequestFactory = new PageRequestFactory();
    public static PropertiesHelper PROPERTIES = PropertiesHelper.getInstance();

	public static String uuid() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	//MD5加解密
	public static String md5encode(String key) {
		return MD5Tool.encode(key);
	}

	public static boolean isEmpty(String val) {
		return StringUtils.isBlank(val);
	}

	/**
	 * Determine whether the given array is empty:
	 * i.e. <code>null</code> or of zero length.
	 * @param array the array to check
	 */
	public static boolean isEmpty(Object[] array) {
		return ObjectUtils.isEmpty(array);
	}

	/**
	 * Determine whether the given object is an array:
	 * either an Object array or a primitive array.
	 * @param obj the object to check
	 */
	public static boolean isArray(Object obj) {
		return ObjectUtils.isArray(obj);
	}

	/**
	 * Check whether the given array contains the given element.
	 * @param array the array to check (may be <code>null</code>,
	 * in which case the return value will always be <code>false</code>)
	 * @param element the element to check for
	 * @return whether the element has been found in the given array
	 */
	public static boolean containsElement(Object[] array, Object element) {
		return ObjectUtils.containsElement(array, element);
	}


    /**
     * <pre>
     * 方法名称：拷贝文件
     * 功能描述：将原文件拷贝给目标文件
     * @param srcfile 原文件 非文件夹
     * @param tagfile 目标文件 非文件夹
     * @throws Exception
     * void
     * </pre>
     */
    public static void copyFile(File srcfile, File tagfile) throws Exception {
        int length = 2097152;
        FileInputStream in = new FileInputStream(srcfile);
        FileOutputStream out = new FileOutputStream(tagfile);
        FileChannel inC = in.getChannel();
        FileChannel outC = out.getChannel();
        ByteBuffer b = null;
        while (true) {
            if (inC.position() == inC.size()) {
                inC.close();
                outC.close();
                break;
            }
            if ((inC.size() - inC.position()) < length) {
                length = (int) (inC.size() - inC.position());
            } else
                length = 2097152;
            b = ByteBuffer.allocateDirect(length);
            inC.read(b);
            b.flip();
            outC.write(b);
            outC.force(false);
        }
    }

    /**
     * <pre>
     * 方法名称：获取文件类型
     * 功能描述：获取文件后缀名
     * @param file 文件对象
     * @return
     * String
     * </pre>
     */
    public static String getFiletype(File file) {
        String filename = file.getName();
        int start = filename.lastIndexOf(".") + 1;
        return filename.substring(start);
    }

    /**
     * <p>Discription: 将指定字符串连续拼接指定次数</p>
     * @param str
     * @param times
     * @return
     * @author       :
     * @update       :
     */
    public static String strAdd(String str, int times) {
        if (times > 0) {
            StringBuffer ret = new StringBuffer();
            for (int i = 0; i < times; i++) {
                ret.append(str);
            }
            return (ret.toString());
        } else {
            return "";
        }
    }

    /**
     * <p>Discription: 给字符串补足到指定的长度，从左边补足chr指定的字符</p>
     * @param source
     * @param chr
     * @param len
     * @return
     * @author       :
     * @update       :
     */
    public static String lPad(String source, String chr, int len) {
        int lenleft = len - source.length();
        if (lenleft < 0) {
            lenleft = 0;
        }
        return (strAdd(chr, lenleft) + source);
    }

    /**
     * <p>Discription: 给字符串补足到指定的长度，从右边补足chr指定的字符</p>
     * @param source
     * @param chr
     * @param len
     * @return
     * @author       :
     * @update       :
     */
    public static String rPad(String source, String chr, int len) {
        int lenleft = len - source.length();
        if (lenleft < 0) {
            lenleft = 0;
        }
        return (source + strAdd(chr, lenleft));
    }

    /**
     * 适合小文件,根据输入流读取文件内容
     *
     * @param fin
     * @return
     */
    public static String getFileContent(InputStream fin) {
        String str = null;
        try {
            byte[] buff = new byte[fin.available()];
            fin.read(buff);
            str = new String(buff);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                fin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    /**
     * <p>
     * 方法描述: 从文件中获取JSON数据,文件内容为标准合法的JSON字符串
     * </p>
     * @return
     * Map<String,Object>
     */
    public static Map<?, ?> getJsonData(InputStream inputStream) {
        String json = getFileContent(inputStream);
        return JSON.fromJSON(json);
    }

	public static void main(String[] args) {
		System.out.println(PL.uuid());
        System.out.println(PL.PROPERTIES.getPropertiesValue("develop"));
        System.out.println(PL.md5encode("111111"));
    }

}
